<template>
    <div>
        <el-card shadow="never" class="mb-5">
            <div class="flex items-center">
                <el-text>分类名称</el-text>
                <div class="ml-3 w-52 mr-5">
                    <el-input v-model="searchCategoryName" placeholder="请输入分类名称"></el-input>
                </div>
                <el-text>创建日期</el-text>
                <div class="ml-3 w-30 mr-5">
                    <el-date-picker style="top:3px" v-model="pickDate" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" size="default"
                        @change="datepickerChange" />
                </div>

                <el-button type="primary" class="ml-3" :icon="Search" @click="getTableData">查询</el-button>
                <el-button type="ml-3" :icon="RefreshRight" @click="reset">重置</el-button>
            </div>
        </el-card>

        <el-card shadow="never">
            <!-- 新增按钮 -->
            <div class="mb-5">
                <el-button type="primary" @click="addCategoryBtnClick">
                    <el-icon class="mr-1">
                        <Plus />
                    </el-icon>
                    新增</el-button>
            </div>

            <!-- 分页列表 -->
            <el-table :data="tableData" border stripe style="width: 100%" v-loading="tableLoading">
                <el-table-column prop="name" label="分类名称" width="180" />
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="danger" size="small" @click="deleteCategorySubmit(scope.row)">
                            <el-icon class="mr-1">
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <div class="mt-10 flex justify-center">
            <el-pagination v-model:current-page="current" v-model:page-sizes="size" :page-sizes="[10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="getTableData">
            </el-pagination>
        </div>

        <!-- 添加文章分类对话框 -->
        <!--<el-dialog v-model="dialogVisible" title="添加文章分类" width="40%" :draggable="true" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <el-form ref="formRef" :rules="rules" :model="form">
            <el-form-item label="分类名称" prop="name" label-width="80px">
                <el-input size="large" v-model="form.name" placeholder="请输入分类名称" show-word-limit clearable />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onSubmit">提 交</el-button>
            </span>
        </template>
    </el-dialog>-->

        <!-- 添加分类 -->
        <FormDialog ref="formDialogRef" title="添加文章分类" destroyOnClose @submit="onSubmit">
            <el-form ref="formRef" :rules="rules" :model="form">
                <el-form-item label="分类名称" prop="name" label-width="80px" size="large">
                    <el-input v-model="form.name" placeholder="请输入分类名称" maxlength="20" show-word-limit clearable />
                </el-form-item>
            </el-form>
        </FormDialog>
    </div>
</template>

<script setup>
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import moment from 'moment'
import { getCategoryPageList, addCategory, deleteCategory } from '@/api/admin/category'
import { showMessage, showModel } from '@/composables/util'
import FormDialog from '@/components/FormDialog.vue'

// 对话框是否显示
const formDialogRef = ref(null)

// 新增分类按钮点击事件
const addCategoryBtnClick = () => {
    formDialogRef.value.open()
}
// 表单引用
const formRef = ref(null)

// 添加文章分类表单对象
const form = reactive({
    name: '',
})
// 规则校验
const rules = {
    name: [
        {
            required: true,
            message: '分类名称不能为空',
            trigger: 'blur',
        },
        {
            min: 1,
            max: 20,
            message: '分类名称长度在 1 到 20 个字符',
            trigger: 'blur',
        },
    ]
}

const onSubmit = () => {
    // 先验证 form 表单字段
    formRef.value.validate((valid) => {
        if (!valid) {
            console.log('表单验证不通过')
            return false
        }
        // 显示按钮 loading
        formDialogRef.value.showBtnLoading()
        addCategory(form).then((res) => {
            if (res.success == true) {
                showMessage('添加成功')
                // 将表单中分类名称置空
                form.name = ''
                // 隐藏对话框
                formDialogRef.value.close()
                // 重新请求分页接口，渲染数据
                getTableData()
            } else {
                // 获取服务端返回的错误消息
                let message = res.message
                // 提示错误消息
                showMessage(message, 'error')
            }
        }).finally(() => {
            // 关闭按钮 loading
            formDialogRef.value.closeBtnLoading()
        })

    })
}

const tableData = ref([])
const current = ref(1)
const size = ref(10)
const total = ref(0)

// 查询条件： 开始时间、结束时间
const startDate = reactive({})
const endDate = reactive({})

const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD')
    endDate.value = moment(e[1]).format('YYYY-MM-DD')

    console.log('开始时间：' + startDate.value + ', 结束时间 ' + endDate.value)
}
// 分页查询的分类情况
const searchCategoryName = ref('')

// 日期选择
const pickDate = ref('')

const shortcuts = [
    {
        text: '最近一周',
        value: () => {
            const start = new Date()
            const end = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '最近一个月',
        value: () => {
            const start = new Date()
            const end = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: '最近三个月',
        value: () => {
            const start = new Date()
            const end = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    }
]
// 表格加载 Loading
const tableLoading = ref(false)
// 获取分页数据
function getTableData() {

    // 显示表格 Loading
    tableLoading.value = true

    // 调用后台分页接口，并传入所需参数
    getCategoryPageList({ current: current.value, size: size.value, startDate: startDate.value, endDate: endDate.value, name: searchCategoryName.value })
        .then(res => {
            if (res.success == true) {
                tableData.value = res.data
                total.value = res.total
                current.value = res.current
                size.value = res.size
            }
        }).finally(() =>
            // 隐藏表格 Loading
            tableLoading.value = false // 隐藏表格 Loading
        )
}
getTableData()

// 每页展示数量变更情况
const handleSizeChange = (chooseSize) => {
    size.value = chooseSize
    getTableData()
}
// 重置查询条件
const reset = () => {
    searchCategoryName.value = ''
    pickDate.value = ''
    startDate.value = null
    endDate.value = null
}

// 删除文章分类
const deleteCategorySubmit = (row) => {
    showModel('删除文章分类', '确定要删除文章分类吗？').then(() => {
        // 调用后台接口，删除文章分类
        deleteCategory(row.id).then(res => {
            if (res.success == true) {
                showMessage('删除成功')
                // 重新请求接口，渲染数据
                getTableData()
            } else {
                // 获取服务端返回的错误消息
                let message = res.message
                // 显示错误消息
                showMessage(message, 'error')
            }
        })
    }).catch(() => {
        console.log('点击了取消按钮')
    })
}

</script>